package com.hethongviet.preventingmachine.helps;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.text.TextUtils;

import com.hethongviet.preventingmachine.Config;
import com.hethongviet.preventingmachine.Constants;
import com.hethongviet.preventingmachine.R;
import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.models.Number;

/** Handle SMS send */
public final class SMSHelperDoor
{
	public static final char CODE_END = '#';
	public static final char CODE_SEPARATE = ',';

	public static final String CODE_SYNCHRONIZE_NUMBERS_CONTROL = "13";
	public static final String CODE_SETUP_PHONE_CONTROL = "11";
	public static final String CODE_UPDATE_PHONE_CONTROL = "SDK";
	public static final String CODE_CHANGE_PIN = "DP";
	public static final String CODE_GET_LOG = "DMC";

	private static String phoneNumberDevice = null;
	private static String pincode = null;

	private static Activity activity = null;

	public static Transaction transaction = null;

	private static Timer timerOutSMS = null;

	public static void cancelTimeout()
	{
		if (timerOutSMS != null)
		{
			timerOutSMS.cancel();
			timerOutSMS = null;
		}

	}

	public static String getDeviceNumber()
	{
		return phoneNumberDevice;
	}

	public static void setPassword(String pass)
	{
		pincode = pass;
	}

	public static void setDeviceNumber(String number)
	{
		phoneNumberDevice = number;
	}

	public static void setActivity(Activity activity1)
	{
		activity = activity1;
	}

	// ---sends an SMS message to another device---
	private static void sendSMS(String number, String code, String message)
	{
		Utils.debug("sendSMS(" + number + ", " + message + ")");

		final String CODE_SENT = "SMS_SENT";
		final String CODE_DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPendingIntent = PendingIntent.getBroadcast(activity,
				0, new Intent(CODE_SENT), 0);

		PendingIntent deliveredPendingIntent = PendingIntent.getBroadcast(
				activity, 0, new Intent(CODE_DELIVERED), 0);

		// ---when the SMS has been sent---
		activity.registerReceiver(new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context arg0, Intent arg1)
			{
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					Utils.toast(activity, R.string.message_SMS_send);
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Utils.toast(activity, R.string.message_error_SMS_send);
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Utils.toast(activity,
							R.string.message_error_SMS_not_available);
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Utils.toast(activity, R.string.message_error_SMS_send);
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Utils.toast(activity, R.string.message_error_SMS_radio_off);
					break;
				}
			}
		}, new IntentFilter(CODE_SENT));

		// ---when the SMS has been delivered---
		activity.registerReceiver(new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context arg0, Intent arg1)
			{
				switch (getResultCode())
				{
				case Activity.RESULT_OK:
					Utils.toast(activity, R.string.message_SMS_deliveried);
					break;
				case Activity.RESULT_CANCELED:
					Utils.toast(activity,
							R.string.message_error_SMS_not_deliveried);
					break;
				}
			}
		}, new IntentFilter(CODE_DELIVERED));

		transaction = new Transaction();
		transaction.setMessageSend(message);
		transaction.setCodeSend(code);
		transaction.setRecipient(number);

		if (!Config.IS_DEBUG_SMS_RECEIVE)
		{
			SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage(number, null, message, sentPendingIntent,
					deliveredPendingIntent);

			Utils.debug("---------Sending message via SMS = " + message);
			Utils.debug("---------Sending message via SMS to " + number);

			timerOutSMS = new Timer();
			TimerTask task = new TimerTask()
			{
				@Override
				public void run()
				{
					activity.runOnUiThread(new Runnable()
					{
						@Override
						public void run()
						{
							Utils.hideProgressDialog();
							Utils.debug("TIME OUT SMS");
							Utils.toast(activity, "Timeout!");
						}
					});
				}
			};

			timerOutSMS.schedule(task, Constants.TIME_OUT_SMS);
		}
	}

	public static void changePassword(String newPassword)
	{
		Utils.debug("change pin!!!!!!");
		if (TextUtils.isEmpty(newPassword))
		{
			Utils.debug("Error: newPassword null!!!!!!");
			return;
		}

		sendSMS(phoneNumberDevice, CODE_CHANGE_PIN, pincode + CODE_SEPARATE
				+ CODE_CHANGE_PIN + newPassword + CODE_END);
	}

	public static void setupNumberControl(List<Number> numbers)
	{
		Utils.debug("setupNumberControl!!!!!!");

		String message = pincode;

		for (Number number : numbers)
		{
			if (number.isActive())
			{
				message += CODE_SEPARATE + "T" + number.getNumber();
			}
			else
			{
				message += CODE_SEPARATE + "X" + number.getNumber();
			}
		}

		sendSMS(phoneNumberDevice, CODE_SETUP_PHONE_CONTROL, message);
	}

	public static void updateNumberControl()
	{
		Utils.debug("updateNumberControl!!!!!!");

		sendSMS(phoneNumberDevice, CODE_UPDATE_PHONE_CONTROL, pincode
				+ CODE_SEPARATE + CODE_UPDATE_PHONE_CONTROL + CODE_END);
	}

	public static void getLog(String startTimeStr, String endTimeStr)
	{
		Utils.debug("getLog!!!!!!");

		sendSMS(phoneNumberDevice, CODE_GET_LOG, pincode + CODE_SEPARATE
				+ CODE_GET_LOG + startTimeStr + ":" + endTimeStr + CODE_END);
	}

	public static void synchronize(String number, String message)
	{
		Utils.debug("Send message sychronize to numbers!!!!!!");
		sendSMS(number, CODE_SYNCHRONIZE_NUMBERS_CONTROL, message + " "
				+ phoneNumberDevice);
	}

}
